package com.smedi.ismedi.progress.core.application.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.cache.starter.util.RedisUtil;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.inmail.api.dto.request.MessageInfoRequest;
import com.smedi.ismedi.organization.api.dto.response.resp.OrganizationResp;
import com.smedi.ismedi.progress.api.dto.response.ProgressReportMonthDetailAllResponse;
import com.smedi.ismedi.progress.api.dto.response.ProgressReportWeekDetailAllResponse;
import com.smedi.ismedi.progress.core.application.command.*;
import com.smedi.ismedi.progress.core.application.query.ProgressReportQueryService;
import com.smedi.ismedi.progress.core.application.service.ProgressReportApplicationService;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.*;
import com.smedi.ismedi.progress.core.domain.dto.PersonQuery;
import com.smedi.ismedi.progress.core.domain.repository.PersonRepository;
import com.smedi.ismedi.progress.core.domain.service.ExportExcelDomainService;
import com.smedi.ismedi.progress.core.domain.service.ProgrressReportDomainService;
import com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.progress.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.progress.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.ProgressReportEntity;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.VersionManageEntity;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.ProgressReportMapper;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.VersionManageMapper;
import com.smedi.ismedi.progress.core.port.adapter.service.MessageRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.ProcessRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.TaskRemoteService;
import com.smedi.ismedi.web.starter.exception.ErrorItem;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.stream.Collectors;

import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.*;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.MethodEnum.NOT_PASS;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.MethodEnum.PASS;
import static com.smedi.ismedi.progress.core.infrastructure.constant.CustomError.DEAL_PERSON_NOT_FOUND;

/**
 * 特种设备应用服务实现类
 *
 * @author xienannan
 * @date 2021/08/28
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ProgressReportApplicationServiceImpl implements ProgressReportApplicationService {

    private final ProcessRemoteService processRemoteService;
    private final TaskRemoteService taskRemoteService;
    private final ProgressReportQueryService progressReportQueryService;
    private final MessageRemoteService messageRemoteService;
    private final AuthorityUtil authorityUtil;
    private final ProgrressReportDomainService progrressReportDomainService;
    private final RedisUtil redisUtil;
    private final ExportExcelDomainService exportExcelDomainService;
    private final AdapterConverter adapterConverter;
    private final PersonRepository personRepository;
    private final ProgressReportMapper progressReportMapper;
    @Value("${message-notify.institution-control.role}")
    private String messageNotifyInstitutionControlRole;//工程管理部控制经理
    @Value("${message-notify.institution-incharge.role}")
    private String messageNotifyInstitutionInchargeRole; //工程管理部分管副总经理
    @Value("${message-notify.institution-generalmanager.role}")
    private String messageNotifyInstitutionGeneralmanagerRole; //工程管理部总经理
    @Value("${message-notify.institution-epcmanager.role}")
    private String messageNotifyInstitutionEpcmanagerRole;//工程总承包经理
    @Value("${message-notify.main-institute.role}")
    private String messageNotifyMainInstituteRole; //主体院EPC分管领导
    @Value("${message-notify.project-manager.role}")
    private String messageNotifyProjectManagerRole;// 施工项目经理
    @Value("${message-notify.project-assistant-manager.role}")
    private String messageNotifyProjectAssistantManagerRole; //施工项目副经理
    @Value("${message-notify.project-epc-manager.role}")
    private String messageNotifyProjectEpcManagerRole; //EPC项目经理
    private final VersionManageMapper versionManageMapper;

    @Override
    public ProjectOne projectInformation(ProgressViewCommand progressViewCommand) {
        String constructionMember = null;
        String ePCMemberMember = null;
        String hrOrganizationFullName = null;
        String name = null;
        List<Person> messageNotifyInstitutionEpcmanager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectEpcManagerRole).projectId(progressViewCommand.getProjectId()).build());//EPC项目经理
        List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(progressViewCommand.getProjectId()).build());//施工项目经理
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(progressViewCommand.getProjectId());
        List<Long>  constructionMemberId = messageNotifyProjectManager.stream().distinct().map(Person::getId).collect(Collectors.toList());
        if (!messageNotifyInstitutionEpcmanager.isEmpty()) {
            List<String> projectName = messageNotifyInstitutionEpcmanager.stream().distinct().map(Person::getName).collect(Collectors.toList());
            ePCMemberMember = StringUtils.strip(projectName.toString(), "[]");
        }
        if (!messageNotifyProjectManager.isEmpty()) {
            List<String> projectName = messageNotifyProjectManager.stream().distinct().map(Person::getName).collect(Collectors.toList());
            constructionMember = StringUtils.strip(projectName.toString(), "[]");

        }
        ProjectOne projectOne = new ProjectOne();
        projectOne.setConstructionMember(constructionMember);
        projectOne.setEPCMember(ePCMemberMember);
        projectOne.setConstructionMemberId(constructionMemberId);
        if (projectData != null) {
            hrOrganizationFullName = projectData.getHrOrganizationFullName();
            name = projectData.getProjectName();
            if (projectData.getContractDurationBegin() != null ){
                projectOne.setContractDurationBegin(projectData.getContractDurationBegin());
            }
            if (projectData.getContractDurationEnd() != null ){
                projectOne.setContractDurationEnd(projectData.getContractDurationEnd());
            }
            if (projectData.getContractDurationDays() != null){
                projectOne.setContractDurationDays(projectData.getContractDurationDays());
            }
            Long projectId = projectData.getProjectId();
            LambdaQueryWrapper<VersionManageEntity> versionManageEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getMainCourtyardApproval,1);
            versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getProjectId,projectId);
            versionManageEntityLambdaQueryWrapper.orderByDesc(VersionManageEntity ::getVersion);
            List<VersionManageEntity> versionManageEntities = versionManageMapper.selectList(versionManageEntityLambdaQueryWrapper);
            if(versionManageEntities.size() > 0){
                projectOne.setIsApproval("1");
                projectOne.setId(versionManageEntities.get(0).getId());
            }else{
                projectOne.setIsApproval("0");
            }
        }
        projectOne.setHrOrganizationFullName(hrOrganizationFullName);
        projectOne.setName(name);
        return projectOne;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProgressReport reviewWeekReportInstitution(ProgressReviewProjectCommand progressReviewProjectCommand) {
        // 根据id 获取 进度周报

        ProgressReport weekReport = progressReportQueryService.getProgressWeekReportOne(ProgressReportOneQuery.builder().id(progressReviewProjectCommand.getId()).build());
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(weekReport.getProjectId());
        String projectName = null;
        String projectId = null;
        String hrOrganizationFullName = null;
        if (projectData != null){
            if (projectData.getProjectName() != null ){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null ){
                projectId = String.valueOf(projectData.getProjectId());
            }
            if (projectData.getHrOrganizationFullName() != null ){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
        }
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, progressReviewProjectCommand.getMethod());
//
        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(progressReviewProjectCommand.getId()))
                .businessType(WEEK_MONTH)
                .processDefinitionKey(PROCESS_REPORT)
                .comment(progressReviewProjectCommand.getComment())
                .variables(variables)
                .build());
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(progressReviewProjectCommand.getId())
                .taskType(TASK_WEEK_REPORT_TYPE)
                .taskName(TASK_NAME_WEEK_REPORT_APPROVAL)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());
        MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
        MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
        List<MessageInfoRequest> listDate = new ArrayList<>();
        messageInfoRequests.setMessageTitle(ConstantField.APPROVAL_RESULTS);
        messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
        messageInfoRequests.setSourceFrom(ConstantField.TASK_WEEK_REPORT_TYPE);
        messageInfoRequests.setProjectId(projectId);
        messageInfoRequests.setProjectName(projectName);
        messageInfoRequests.setPushTime(LocalDateTime.now());
        if (progressReviewProjectCommand.getMethod().equals(PASS.name())) {
            weekReport.setTaskStatus(FINISHED);
            weekReport.setTaskKey(ACTIVITY_FINISH);
            weekReport.setConstructionManagerApproval(1l);
            weekReport.setStatus(1l);
            // 更新项目主表字段
            progrressReportDomainService.updateReportDetailToProject(weekReport);
            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_TEMPLATE_WEEK_PASS)
                    .mobiles(new ArrayList<>(Collections.singletonList(weekReport.getPerson().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(weekReport.getPerson().getName(), weekReport.getProject().getName(),TASK_WEEK_REPORT_TYPE)))
                    .build());
            // 周报审批通过后，判断是否有里程碑和关键任务滞后7天内  施工项目经理、工程总承包经理
            List<Map<String,Object>> dateSUM = progrressReportDomainService.milestoneAndKeyLagging7(weekReport);
            List<Person> prosenDate = new ArrayList<>();
            List<Person> prosenDate1 = new ArrayList<>();
            List<Person> prosenDate2 = new ArrayList<>();
            List<String> person = new ArrayList<>();
            person.add(messageNotifyProjectEpcManagerRole);//EPC项目经理
            person.add(messageNotifyProjectManagerRole);// 施工项目经理
            List<Person> epcAndProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJobs(person).projectId(weekReport.getProjectId()).build());//EPC项目经理 与 施工项目经理
            //工程管理部分管副总经理
            List<String> personTwo = new ArrayList<>();
            personTwo.add(messageNotifyMainInstituteRole);//主体院EPC分管领导
            List<Person> messageNotifyMainInstitute = personRepository.getPersonList(PersonQuery.builder().roleNames(personTwo).organizationId(weekReport.getProject().getHrOrganizationId()).build());//主体院EPC分管领导
            //取epc 施工经理 、主体院 分管领导
            List<String> personThree = new ArrayList<>();
            personThree.add(messageNotifyInstitutionControlRole);//工程管理部控制经理（新建角色）
            personThree.add(messageNotifyInstitutionInchargeRole);//工程管理部分管副总经理（新建角色）
            personThree.add(messageNotifyInstitutionGeneralmanagerRole);//工程管理部总经理（新建角色）
            List<Person> messageRoleNames = personRepository.getPersonList(PersonQuery.builder().roleNames(personThree).build());
            List<Person> messageNotifyInstitutionControl = personRepository.getPersonList(PersonQuery.builder().roleName(messageNotifyInstitutionControlRole).build()); // 工程管理部控制经理（新建角色）

            String messageContent = null;
            String messageTitle = null;
            String messageType = "系统消息";
            for (int i = 0; i < dateSUM.size(); i++) {
                //周报审批通过后，判断是否有里程碑和关键任务滞后超过2周  施工项目经理、EPC项目经理、主体院EPC分管领导、工程管理部控制经理（新建角色）、工程管理部分管副总经理（新建角色）、工程管理部总经理（新建角色）
                if ("3".equals(dateSUM.get(i).get("statusType")) && Integer.valueOf(dateSUM.get(i).get("countSum").toString()) != 0) {
                    messageContent = projectName + "滞后，共" + dateSUM.get(i).get("countSum") + "个里程碑/关键任务滞后超过20天：分别是" + dateSUM.get(i).get("name");
                    messageTitle = "项目任务滞后超过20天";
                    prosenDate.addAll(epcAndProjectManager); // epc/施工项目经理
                    prosenDate.addAll(messageNotifyMainInstitute);//主体院EPC分管领导
                    prosenDate.addAll(messageRoleNames);//工程管理部控制经理（新建角色）、工程管理部分管副总经理（新建角色）、工程管理部总经理（新建角色）

                    this.postMessage(weekReport, messageContent, messageTitle, messageType, prosenDate, projectData);
                }
                // 周报审批通过后，判断是否有里程碑和关键任务滞后7天内  施工项目经理、EPC项目经理
                if ("1".equals(dateSUM.get(i).get("statusType")) && Integer.valueOf(dateSUM.get(i).get("countSum").toString()) != 0) {
                    messageContent = projectName + "滞后，共" + dateSUM.get(i).get("countSum") + "个里程碑/关键任务滞后：分别是" + dateSUM.get(i).get("name");
                    messageTitle = "项目任务滞后";
                    prosenDate1.addAll(epcAndProjectManager);//EPC项目经理、施工经理
                    this.postMessage(weekReport, messageContent, messageTitle, messageType, prosenDate1, projectData);
                }
                //周报审批通过后，判断是否有里程碑和关键任务滞后7-14天  施工项目经理、EPC项目经理、主体院EPC分管领导、工程管理部控制经理（新建角色）
                if ("2".equals(dateSUM.get(i).get("statusType")) && Integer.valueOf(dateSUM.get(i).get("countSum").toString()) != 0) {
                    messageContent = projectName + "滞后，共" + dateSUM.get(i).get("countSum") + "个里程碑/关键任务滞后超过7-20天：分别是" + dateSUM.get(i).get("name");
                    messageTitle = "项目任务滞后超过7-20天";
                    prosenDate2.addAll(epcAndProjectManager);//EPC项目经理、施工
                    prosenDate.addAll(messageNotifyMainInstitute);//主体院EPC分管领导
                    prosenDate2.addAll(messageNotifyInstitutionControl);//工程管理部控制经理（新建角色）
                    this.postMessage(weekReport, messageContent, messageTitle, messageType, prosenDate2, projectData);
                }
            }
            //周报审批通过后，判断是否有里程碑和关键任务滞后7-14天  施工项目经理、工程总承包经理、主体院分管领导、工程管理部控制经理
            //周报审批通过后，判断是否有里程碑和关键任务滞后超过2周  施工项目经理、工程总承包经理、主体院分管领导、工程管理部控制经理、工程管理部分管副总经理、工程管理部总经理
            // 发送消息
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START + hrOrganizationFullName + "的" + projectName + ConstantField.TASK_WEEK_REPORT_TYPE + ConstantField.MESSAGE_CONTENT_PASS_END);
        }
        if (progressReviewProjectCommand.getMethod().equals(NOT_PASS.name())) {
            weekReport.setTaskStatus(processTask.getStatus());
            weekReport.setTaskKey(processTask.getTaskDefinitionKey());
            weekReport.setConstructionManagerApproval(2l);
            weekReport.setStatus(0l);
            weekReport.setReason(progressReviewProjectCommand.getComment());
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_TEMPLATE_WEEK_REPORT_BACK)
                    .mobiles(new ArrayList<>(Collections.singletonList(weekReport.getPerson().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(weekReport.getPerson().getName(), weekReport.getProject().getName(),TASK_WEEK_REPORT_TYPE)))
                    .build());
            taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                    .sourceFromId(weekReport.getId())
                    .taskType(TASK_WEEK_REPORT_TYPE)
                    .taskName(TASK_NAME_WEEK_REPORT_BACK)
                    .taskDescribe(ConstantField.WEEK_REPORT_NAME)
                    .taskStatus("进行中")
                    .dealPersonId(weekReport.getPerson().getId())
                    .dealPersonName(weekReport.getPerson().getName())
                    .projectId(Long.parseLong(projectId))
                    .projectName(projectName)
                    .sponsorId(authorityUtil.getPersonId())
                    .sponsorName(authorityUtil.getLoginAccess().getLastName())
                    .startTime(LocalDateTime.now())
                    .build());
            // 发送消息
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START + hrOrganizationFullName +"的"+ projectName + ConstantField.TASK_WEEK_REPORT_TYPE+ConstantField.MESSAGE_CONTENT_NO_PASS_END);
//            messageInfoRequests.setSourceFrom(TASK_WEEK_REPORT_TYPE);

        }
        listDate.add(messageInfoRequests);
        messagesSendPostCommand.setMessageInfoRequests(listDate);
        messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(weekReport.getPerson().getId())));
        taskRemoteService.postSendMessage(messagesSendPostCommand);
        return progrressReportDomainService.updateProgressReport(weekReport);
    }

    private void postMessage(ProgressReport progressReport, String messageContent, String messageTitle, String messageType,List<Person> person,ProjectBasicResponse projectData){
        String hrOrganizationFullName = null;
        String projectName = null;
        String projectId = null;
        if (projectData != null){
            if (projectData.getHrOrganizationFullName() != null){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
            if (projectData.getProjectName() != null){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null){
                projectId = String.valueOf(projectData.getProjectId());
            }
        }
        if (!person.isEmpty()){
            List<Person> newPerson = person.stream().distinct().collect(Collectors.toList());
            for (Person person1 : newPerson){
                messageRemoteService.sendMessage(MessageSendCommand.builder()
                        .smsTemplateName(SMS_TEMPLATE_WEEK_LAGGING)
                        .mobiles(new ArrayList<>(Collections.singletonList(person1.getMobile())))
                        .parameters(new ArrayList<>(Arrays.asList(person1.getName(),hrOrganizationFullName,messageContent)))
                        .build());
            }
        }

        List<MessageInfoRequest> listDate = new ArrayList<>();

        MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
        MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
        messageInfoRequests.setMessageContent(messageContent);
        messageInfoRequests.setMessageTitle(messageTitle);
        messageInfoRequests.setMessageType(messageType);
        messageInfoRequests.setProjectId(projectId);
        messageInfoRequests.setProjectName(projectName);
        messageInfoRequests.setPushTime(LocalDateTime.now());
        messageInfoRequests.setSourceFrom(TASK_WEEK_REPORT_TYPE);
        listDate.add(messageInfoRequests);
        messagesSendPostCommand.setMessageInfoRequests(listDate);
        messagesSendPostCommand.setUserIds(person.stream().distinct().map(Person -> Person.getId()).collect(Collectors.toList()));
        taskRemoteService.postSendMessage(messagesSendPostCommand);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProgressReport reviewMonthReportInstitution(ProgressReviewProjectCommand progressReviewProjectCommand) {
        // 根据id 获取 进度月报
        log.info("开始进度周、月报审核，数据ID："+progressReviewProjectCommand.getId()+",审核处理方式："+progressReviewProjectCommand.getMethod()+",审核处理意见："+progressReviewProjectCommand.getComment());
        ProgressReport monnthReport = progressReportQueryService.getProgressWeekReportOne(ProgressReportOneQuery.builder().id(progressReviewProjectCommand.getId()).build());
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, progressReviewProjectCommand.getMethod());
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(monnthReport.getProjectId());
        String projectName = null;
        String projectId = null;
        String hrOrganizationFullName = null;
        if (projectData != null){
            if (projectData.getProjectName() != null ){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null ){
                projectId = String.valueOf(projectData.getProjectId());
            }
            if (projectData.getHrOrganizationFullName() != null ){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
        }
        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(progressReviewProjectCommand.getId()))
                .businessType(WEEK_MONTH)
                .processDefinitionKey(PROCESS_REPORT)
                .comment(progressReviewProjectCommand.getComment())
                .variables(variables)
                .build());
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(progressReviewProjectCommand.getId())
                .taskType(TASK_MONTH_REPORT_TYPE)
                .taskName(TASK_NAME_MONTH_REPORT_APPROVAL)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());
        MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
        MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
        List<MessageInfoRequest> listDate = new ArrayList<>();
        messageInfoRequests.setMessageTitle(ConstantField.APPROVAL_RESULTS);
        messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
        messageInfoRequests.setProjectId(projectId);
        messageInfoRequests.setProjectName(projectName);
        messageInfoRequests.setPushTime(LocalDateTime.now());
        if (progressReviewProjectCommand.getMethod().equals(PASS.name())) {

            monnthReport.setTaskStatus(ConstantField.FINISHED);
            monnthReport.setTaskKey(ConstantField.ACTIVITY_FINISH);
            monnthReport.setConstructionManagerApproval(1l);
            monnthReport.setStatus(1l);
            // 更新项目主表字段
            log.info("进度周、月报审核，审核通过，开始更新项目主表字段，主表ID："+monnthReport.getId()+"，数据状态："+monnthReport.getStatus()+"，施工经理审批状态："+monnthReport.getConstructionManagerApproval());
            progrressReportDomainService.updateReportDetailToProject(monnthReport);
            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_TEMPLATE_MONTH_PASS)
                    .mobiles(new ArrayList<>(Collections.singletonList(monnthReport.getPerson().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(monnthReport.getPerson().getName(), monnthReport.getProject().getName(),TASK_MONTH_REPORT_TYPE)))
                    .build());

            // 发送消息
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START +hrOrganizationFullName + "的"+ projectName + ConstantField.TASK_MONTH_REPORT_TYPE+ConstantField.MESSAGE_CONTENT_PASS_END);
            log.info("进度周、月报审核，审核不通过，开始更新项目主表字段，主表ID："+monnthReport.getId()+"，数据状态："+monnthReport.getStatus()+"，施工经理审批状态："+monnthReport.getConstructionManagerApproval());
            //            messageInfoRequests.setSourceFrom(TASK_WEEK_REPORT_TYPE);
        }
        if (progressReviewProjectCommand.getMethod().equals(NOT_PASS.name())) {
            monnthReport.setTaskStatus(processTask.getStatus());
            monnthReport.setTaskKey(processTask.getTaskDefinitionKey());
            monnthReport.setConstructionManagerApproval(2l);
            monnthReport.setStatus(0l);
            monnthReport.setReason(progressReviewProjectCommand.getComment());

            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(ConstantField.SMS_TEMPLATE_MONTH_REPORT_BACK)
                    .mobiles(new ArrayList<>(Collections.singletonList(monnthReport.getPerson().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(monnthReport.getPerson().getName(), monnthReport.getProject().getName(),TASK_MONTH_REPORT_TYPE)))
                    .build());
            // 发送待办
            taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                    .sourceFromId(monnthReport.getId())
                    .taskType(ConstantField.TASK_MONTH_REPORT_TYPE)
                    .taskName(ConstantField.TASK_NAME_MONTH_REPORT_BACK)
                    .taskDescribe(ConstantField.MONTH_REPORT_NAME)
                    .taskStatus("进行中")
                    .dealPersonId(monnthReport.getPerson().getId())
                    .dealPersonName(monnthReport.getPerson().getName())
                    .projectId(monnthReport.getProjectId())
                    .projectName(monnthReport.getName())
                    .sponsorId(authorityUtil.getPersonId())
                    .sponsorName(authorityUtil.getLoginAccess().getLastName())
                    .startTime(LocalDateTime.now())
                    .build());
            // 发送消息
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START +hrOrganizationFullName + "的" + projectName + ConstantField.TASK_MONTH_REPORT_TYPE+ConstantField.MESSAGE_CONTENT_NO_PASS_END);
            log.info("进度周、月报审核，审核不通过，开始更新项目主表字段，主表ID："+monnthReport.getId()+"，数据状态："+monnthReport.getStatus()+"，施工经理审批状态："+monnthReport.getConstructionManagerApproval());
        }
        listDate.add(messageInfoRequests);
        messagesSendPostCommand.setMessageInfoRequests(listDate);
        messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(monnthReport.getPerson().getId())));
        taskRemoteService.postSendMessage(messagesSendPostCommand);
        log.info("进度周、月报更新数据，ID："+monnthReport.getId()+"，数据状态："+monnthReport.getStatus()+"，施工经理审批状态："+monnthReport.getConstructionManagerApproval());
        return progrressReportDomainService.updateProgressReport(monnthReport);
    }

    @Override
    public String monthWeekReportSaveDraftAndRelease(WeekMonthReportEidt weekMonthReportEidt) {
        List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(weekMonthReportEidt.getProjectId()).build());
        if (messageNotifyProjectManager.isEmpty()){
//            throw LogicException.raise(new ErrorItem(30, "未找到对应项目的施工项目经理角色，请配置施工项目经理角色"));
            throw LogicException.raise(DEAL_PERSON_NOT_FOUND, weekMonthReportEidt.getName(), this.messageNotifyProjectManagerRole, PORJECT_JOB);
        }
        // 获取 方法判断是保存还是发布 如果是发布的话需要启动审批流程
        //this.validKey(weekMonthReportEidt.getBusinessToken());
        WeekMonthReportEidt weekMonthReportEidtNew = progrressReportDomainService.saveReportAndDetial(weekMonthReportEidt);
        WeekMonthReportEidt weekMonthReportEidtQuery = progrressReportDomainService.getWeekMonthReportOne(weekMonthReportEidtNew);

        // 保存草稿
        if (weekMonthReportEidt.getMethod() == DRAFT_METHOD){
            return null;
        }
        // 周月报发布还需要判断下是否  判断：统计时段的开始时间，必须晚于已发布报告的截止时间。
        // 如果存在就不能发布 提示 发布内容
        Integer timeCount = progrressReportDomainService.findTimeCount(weekMonthReportEidtQuery);
        // 发布 RELEASE RELEASE
        if (RELEASE_METHOD.equals(weekMonthReportEidt.getMethod()) && timeCount == 0){
            // 月报
            if (weekMonthReportEidtQuery.getType() == MONTH_TYPE){
//                LocalDateTime statisticalTime = LocalDateTime.parse(weekMonthReportEidtQuery.getStatisticalTime() + "-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//                LocalDateTime statisticalStartTime  = statisticalTime.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
//                LocalDateTime statisticalEndTime  = statisticalTime.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
//                weekMonthReportEidtQuery.setStatisticalStartTime(statisticalStartTime);
//                weekMonthReportEidtQuery.setStatisticalEndTime(statisticalEndTime);
                this.review(weekMonthReportEidtQuery,TASK_MONTH_REPORT_TYPE,TASK_NAME_MONTH_REPORT_APPROVAL,MONTH_PROGRESS_MESSAGE,SMS_TEMPLATE_MONTH_REPORT_APPROVAL,TASK_NAME_MONTH_REPORT_BACK,messageNotifyProjectManager);
            }
            // 周报
            if (weekMonthReportEidtQuery.getType() == WEEK_TYPE){
                this.review(weekMonthReportEidtQuery,TASK_WEEK_REPORT_TYPE,TASK_NAME_WEEK_REPORT_APPROVAL,WEEK_PROGRESS_MESSAGE,SMS_TEMPLATE_WEEK_REPORT_APPROVAL,TASK_NAME_WEEK_REPORT_BACK,messageNotifyProjectManager);
            }
        }else if (RELEASE_METHOD.equals(weekMonthReportEidt.getMethod())){
            throw LogicException.raise(new ErrorItem(26, "统计时段的开始时间，必须晚于已发布报告的截止时间"));
        }
        return null;
    }

    @Override
    public ResponseEntity<byte[]> progressMonthWeekReportBatchExport(ProgressReportExportQuery progressReportExportQuery) throws IOException {
        if (progressReportExportQuery == null) {
            throw LogicException.raise(CustomError.NO_DATA_FOUND);
        }

        List<ProgressReportMonthDetailAllResponse> progressReportMonthDetailAllResponses = new ArrayList<>();
        if (progressReportExportQuery.getExportType() == 1) {
            log.info("月报导出");
            //progressReportMonthDetailAllResponses = progressReportQueryService.getProgressMonthReportDetailBatch(progressReportExportQuery);
        } else if (progressReportExportQuery.getExportType() == 2){
            log.info("周报导出");
            //progressReportMonthDetailAllResponses = progressReportQueryService.getProgressMonthReportDetailBatch(progressReportExportQuery);
        }
        for(Long id : progressReportExportQuery.getIds()){
            ProgressReportExportQuery temp = new ProgressReportExportQuery();
            temp.setId(id);
            temp.setProjectId(progressReportExportQuery.getProjectId());
            ProgressReportMonthDetailAllResponse detail = progressReportQueryService.getProgressMonthReportDetail(temp);
            progressReportMonthDetailAllResponses.add(detail);
        }
        if (CollectionUtils.isEmpty(progressReportMonthDetailAllResponses)) {
            throw LogicException.raise(CustomError.NO_DATA_FOUND);
        }
        return exportExcelDomainService.exportProgressMonthReport(progressReportMonthDetailAllResponses, progressReportExportQuery.getExportType());
    }

    private void review(WeekMonthReportEidt weekMonthReportEidtQuery, String taskReportType, String taskNameReportApproval, String reportName, String smsTemplateReportApproval, String approvalBak, List<Person> messageNotifyProjectManager) {
        if (null ==  weekMonthReportEidtQuery.getConstructionManagerApproval()){
            processRemoteService.startProcessInstance(ProcessInstanceStartCommand.builder()
                    .businessCode(String.valueOf(weekMonthReportEidtQuery.getId()))
                    .businessType(WEEK_MONTH)
                    .processDefinitionKey(PROCESS_REPORT)
                    .build());
        }
        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(weekMonthReportEidtQuery.getId()))
                .businessType(WEEK_MONTH)
                .processDefinitionKey(PROCESS_REPORT)
                .build());
        weekMonthReportEidtQuery.setTaskStatus(processTask.getStatus());
        weekMonthReportEidtQuery.setTaskKey(processTask.getTaskDefinitionKey());
        weekMonthReportEidtQuery.setConstructionManagerApproval(0l);
        weekMonthReportEidtQuery.setStatus(2l);

        //审批退回后，重新编辑提交时，需要把退回的待办变成已处理
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(weekMonthReportEidtQuery.getId())
                .taskType(taskReportType)
                .taskName(approvalBak)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());

        // 找到 项目施工经理
        // 根据项目id获取施工经理
//        ProjectBasicResponse projectData = progrressReportDomainService.getProject(weekMonthReportEidtQuery.getProjectId());

        for (Person person : messageNotifyProjectManager){
            // 发送待办
            taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                    .sourceFromId(weekMonthReportEidtQuery.getId())
                    .taskType(taskReportType)
                    .taskName(taskNameReportApproval)
                    .taskDescribe(reportName)
                    .dealPersonId(person.getId())// 施工经理id
                    .dealPersonName(person.getName()) // 施工经理名称
                    .taskStatus("进行中")
                    .projectId(weekMonthReportEidtQuery.getProjectId())
                    .projectName(weekMonthReportEidtQuery.getName())
                    .sponsorId(authorityUtil.getPersonId())
                    .sponsorName(authorityUtil.getLoginAccess().getLastName())
                    .startTime(LocalDateTime.now())
                    .build());

//            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(ConstantField.WEEK_MONTH_PREGRESS)
                    .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile()))) // 施工经理是手机号
                    .parameters(new ArrayList<>(Arrays.asList(person.getName(), taskReportType,weekMonthReportEidtQuery.getName())))// 施工经理名称
                    .build());
        }

        ProgressReport ProgressReport = adapterConverter.weekMonthReportEidtQueryToProgressReport(weekMonthReportEidtQuery);
        progrressReportDomainService.updateProgressReport(ProgressReport);
    }

    /**
     * 保证接口幂等
     */
    private void validKey(String token) {
        if (redisUtil.incr(PROGRESS_TOKEN_KEY + COLONS + token, 1) != 2) {
            throw LogicException.raise(CustomError.DUPLICATE_REQUEST);
         }
     }
    @Override
    public Boolean weekReportNews() {
        // 获取所有的项目
        List<ProgressReportEntity> listProgress = progrressReportDomainService.getAllProgressReport();
        WeekFields weekFields= WeekFields.ISO;
        LocalDateTime localDate1  = LocalDateTime.now().with(weekFields.dayOfWeek(), 1L);
        // 判断 当前时间 段是否有周报 未发布 无发送待办任务处理查看到编辑页面，每周日6点还未发布（包含休息日、节假日）
//        LocalDateTime firstDay = localDate1.withHour(0).withMinute(0).withSecond(0);
        String firstDay = DateUtil.format(localDate1.withHour(0).withMinute(0).withSecond(0),"yyyy-MM-dd HH:mm:ss");
        listProgress.forEach(v->{
            ProjectBasicResponse projectData = progrressReportDomainService.getProject(v.getProjectId());
            // 根据项目id获取施工经理
//            ProjectBasicResponse projectData = progrressReportDomainService.getProject(v.getProjectId());
            // 施工项目副经理
            List<Person> messageNotifyProjectAssistantManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectAssistantManagerRole).projectId(v.getProjectId()).build());

            Integer counet = progrressReportDomainService.findWeekReport(firstDay,ConstantField.WEEK_TYPE,v.getProjectId(),v.getId(),ConstantField.WEEK_MONTH_DRAFT_STATUS);
            if(counet > 0){
                if(projectData.getProjectStatus().equals("CONSTRUCTING")){
                    //项目状态为建设中
                    for (Person person : messageNotifyProjectAssistantManager){
                        // 发送待办
                        taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                                .sourceFromId(v.getId())
                                .taskType(TASK_WEEK_REPORT_TYPE)
                                .taskName(WEEK_NOT_RELEASE)
                                .taskDescribe(WEEK_MESSAGE)
                                .taskStatus("进行中")
                                .dealPersonId(person.getId())
                                .dealPersonName(person.getName())
                                .projectId(v.getProjectId())
                                .projectName(v.getName())
                                .sponsorName(SYSTEM_RELEASE)
                                .startTime(LocalDateTime.now())
                                .build());
                    }
                }

            }
        });
        return true;
    }

    @Override
    public Boolean monthReportNews() {
        // 获取所以的项目
        List<ProgressReportEntity> listProgress = progrressReportDomainService.getAllProgressReport();
        // 判断当前月 时间段是否有月报 未发布 无 进度月报，每个建设中项目，每月18号6点还未发布（包含休息日、节假日）
//        WeekFields weekFields= WeekFields.ISO;
//        LocalDateTime localDate1  = LocalDateTime.now().with(weekFields.dayOfWeek(), 1L);
//        LocalDateTime firstDay = localDate1.withHour(0).withMinute(0).withSecond(0);
        // 发送待办
        listProgress.forEach(v->{
            // 根据项目id获取施工经理
//            ProjectBasicResponse projectData = progrressReportDomainService.getProject(v.getProjectId());
            List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(v.getProjectId()).build());

            Integer counet = progrressReportDomainService.findMonthReport(ConstantField.MONTH_TYPE,v.getProjectId(),v.getId(),ConstantField.WEEK_MONTH_DRAFT_STATUS);
            // 是否有这个项目
//            Integer counetNo = progrressReportDomainService.findMonthNoReport(ConstantField.MONTH_TYPE,v.getProjectId());
//            if(counet > 0 || counetNo == 0){
            if(counet > 0){
                for (Person person : messageNotifyProjectManager){
                    // 发送待办
                    taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                            .sourceFromId(v.getId())
                            .taskType(TASK_MONTH_REPORT_TYPE)
                            .taskName(MONTH_NOT_RELEASE)
                            .taskDescribe(MONTH_MESSAGE)
                            .taskStatus("进行中")
                            .dealPersonId(person.getId())
                            .dealPersonName(person.getName())
                            .projectId(v.getProjectId())
                            .projectName(v.getName())
                            .sponsorName(SYSTEM_RELEASE)
                            .startTime(LocalDateTime.now())
                            .build());
                }
             }

        });
        return true;
    }

    @Override
    @Transactional
    public void AutoApproveReturn(Progress versionManage) {
        LambdaQueryWrapper<ProgressReportEntity> prpgressReport = new LambdaQueryWrapper<>();
        prpgressReport.eq(ObjectUtils.isNotNull(versionManage.getProjectId()), ProgressReportEntity::getProjectId, versionManage.getProjectId());
        prpgressReport.eq(ProgressReportEntity::getStatus, 2l);
        prpgressReport.eq(ProgressReportEntity::getConstructionManagerApproval,0l);
        List<ProgressReportEntity> progressReports = progressReportMapper.selectList(prpgressReport);
        progressReports.forEach(v->{
            //  更新 周月报表 状态
            progressReportMapper.updateStuts(v);
            // 修改待办状态
            if (v.getType() == ConstantField.WEEK_TYPE){
                // 周月报自动退回
                AutoApproveBack(v,TASK_WEEK_REPORT_TYPE,TASK_NAME_WEEK_REPORT_APPROVAL,SMS_TEMPLATE_WEEK_REPORT_BACK,TASK_NAME_WEEK_REPORT_BACK,WEEK_REPORT_NAME);
            }else if (v.getType() == ConstantField.MONTH_TYPE){
                AutoApproveBack(v,TASK_MONTH_REPORT_TYPE,TASK_NAME_MONTH_REPORT_APPROVAL,SMS_TEMPLATE_MONTH_REPORT_BACK,TASK_NAME_MONTH_REPORT_BACK,MONTH_REPORT_NAME);
            }
        });
    }

    private void AutoApproveBack(ProgressReportEntity v, String taskWeekReportType, String taskNameWeekReportApproval, String smsTemplateWeekReportBack, String taskNameWeekReportBack, String weekReportName) {
        List<Person> people = personRepository.getPersonList(PersonQuery.builder().ids(new ArrayList<>(Collections.singletonList(v.getCreatedUserId()))).build());
        Map<Long, Person> idPeopleMap = new HashMap<>();
        for (Person application : people) {
            idPeopleMap.put(application.getId(), application);
        }
        Person persond = idPeopleMap.getOrDefault(v.getCreatedUserId(), new Person(v.getCreatedUserId()));
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, NOT_PASS.name());
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(v.getProjectId());
        String projectName = null;
        String projectId = null;
        String hrOrganizationFullName = null;
        if (projectData != null){
            if (projectData.getProjectName() != null ){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null ){
                projectId = String.valueOf(projectData.getProjectId());
            }
            if (projectData.getHrOrganizationFullName() != null ){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
        }
        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(v.getId()))
                .businessType(WEEK_MONTH)
                .processDefinitionKey(PROCESS_REPORT)
                .comment(AUTO_APPROVE_BACK)
                .variables(variables)
                .build());

        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(v.getId())
                .taskType(taskWeekReportType)
                .taskName(taskNameWeekReportApproval)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());

        taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                .sourceFromId(v.getId())
                .taskType(taskWeekReportType)
                .taskName(taskNameWeekReportBack)
                .taskDescribe(ConstantField.AUTO_APPROVE_BACK)
                .taskStatus("进行中")
                .dealPersonId(v.getCreatedUserId())
                .dealPersonName(persond.getName())
                .projectId(Long.parseLong(projectId))
                .projectName(projectName)
//                .sponsorId(authorityUtil.getPersonId())
                .sponsorName(ConstantField.SYSTEM_CREATE)
                .startTime(LocalDateTime.now())
                .build());
        messageRemoteService.sendMessage(MessageSendCommand.builder()
                .smsTemplateName(smsTemplateWeekReportBack)
                .mobiles(new ArrayList<>(Collections.singletonList(persond.getMobile())))
                .parameters(new ArrayList<>(Arrays.asList(persond.getName(), projectName,taskWeekReportType)))
                .build());

        MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
        MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
        List<MessageInfoRequest> listDate = new ArrayList<>();
        messageInfoRequests.setMessageTitle(ConstantField.APPROVAL_RESULTS);
        messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
        messageInfoRequests.setProjectId(projectId);
        messageInfoRequests.setProjectName(projectName);
        messageInfoRequests.setPushTime(LocalDateTime.now());
        messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START + hrOrganizationFullName +"的"+ projectName + taskWeekReportType +ConstantField.MESSAGE_CONTENT_NO_PASS_END);
        listDate.add(messageInfoRequests);
        messagesSendPostCommand.setMessageInfoRequests(listDate);
        messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(v.getCreatedUserId())));
        taskRemoteService.postSendMessage(messagesSendPostCommand);
    }

    @Override
    public Boolean monthReportContext() {
        // 获取所以的项目
        List<ProgressReportEntity> listProgress = progrressReportDomainService.getAllProgressReport();
        listProgress.forEach(v->{
            ProjectBasicResponse projectData = progrressReportDomainService.getProject(v.getProjectId());
            String projectName = null;
            if (projectData != null){
                if (projectData.getProjectName() != null ){
                    projectName = projectData.getProjectName();
                }
            }
            // 施工项目经理
            List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(v.getProjectId()).build());
            String firstDay = LocalDate.now().toString();
            Integer counetNo = progrressReportDomainService.findMonthNoReport(ConstantField.MONTH_TYPE,v.getProjectId());
            if(counetNo == 0){
                if(projectData.getProjectStatus().equals("CONSTRUCTING")){
                    //项目状态为建设中
                    for (Person person : messageNotifyProjectManager){
                        // 发送消息
                        MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
                        MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
                        List<MessageInfoRequest> listDate = new ArrayList<>();
                        messageInfoRequests.setMessageTitle(ConstantField.MONTH_NOT_RELEASE);
                        messageInfoRequests.setMessageType(ConstantField.TASK_MONTH_REPORT_TYPE);
                        messageInfoRequests.setProjectId(String.valueOf(v.getProjectId()));
                        messageInfoRequests.setProjectName(projectName);
                        messageInfoRequests.setPushTime(LocalDateTime.now());
                        messageInfoRequests.setSourceFrom(ConstantField.TASK_MONTH_REPORT_TYPE);
                        // 发送消息
                        messageInfoRequests.setMessageContent(person.getName() + ConstantField.PROGRESS_MONTH_CONTEXT + projectName + "。");
                        messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(person.getId())));
                        listDate.add(messageInfoRequests);
                        messagesSendPostCommand.setMessageInfoRequests(listDate);
                        taskRemoteService.postSendMessage(messagesSendPostCommand);
                    }
                }

            }
        });
        return true;
    }

    @Override
    public void sendMessageNotifyProjectManagerRole(Long projectId) {
//给施工项目经理发送短信以及消息
        // 施工项目经理
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(projectId);
        List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(projectId).build());
        for (Person person : messageNotifyProjectManager){
            // 发送消息
            MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
            MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
            List<MessageInfoRequest> listDate = new ArrayList<>();
            messageInfoRequests.setMessageTitle(ConstantField.TASK_TYPE);
            messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
            messageInfoRequests.setProjectId(String.valueOf(projectId));
            messageInfoRequests.setProjectName(projectData.getProjectName());
            messageInfoRequests.setPushTime(LocalDateTime.now());
            messageInfoRequests.setSourceFrom(ConstantField.TASK_TYPE);
            // 发送消息
            messageInfoRequests.setMessageContent(person.getName() + ConstantField.MESSAGE_CANCEL_VERSION_START + projectData.getProjectName() + ConstantField.MESSAGE_CANCEL_VERSION_END);
            messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(person.getId())));
            listDate.add(messageInfoRequests);
            messagesSendPostCommand.setMessageInfoRequests(listDate);
            taskRemoteService.postSendMessage(messagesSendPostCommand);

            //发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(ConstantField.WEEK_MONTH_ENGINEERING_APPROVAL)
                    .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(person.getName(),projectData.getProjectName())))
                    .build());
        }
    }
}
